{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# dataFrame",
   "id": "6120b11a18368ec1"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-31T09:31:24.133632Z",
     "start_time": "2025-07-31T09:31:24.108085Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "s1 = pd.Series([1,2,3,4,5])\n",
    "s2 = pd.Series([6,7,8,9,10])\n",
    "s3 = pd.Series(['6','7','8','9','10'])\n",
    "df = pd.DataFrame({\"一\":s1,\"二\":s2,\"三\":s3})\n",
    "print(df)\n",
    "\n",
    "#使用数组创建dataFrame，一行一行的数据\n",
    "df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9],[10,11,12]],columns=[\"一\",\"二\",\"三\"],index=[\"1:\",\"2:\",\"3:\",\"4:\"])\n",
    "print( df)\n",
    "#直接声明{[]}创建，一列一列的数据作为数组\n",
    "df = pd.DataFrame({\n",
    "    \"一\":[1,2,3,4],\n",
    "    \"二\":[5,6,7,8],\n",
    "    \"三\":[9,10,11,12]\n",
    "},index=[\"a\",\"b\",\"c\",\"d\"],columns=[\"一\",\"二\",\"三\"])\n",
    "print(df)\n"
   ],
   "id": "e2d18a0672b15a56",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   一   二   三\n",
      "0  1   6   6\n",
      "1  2   7   7\n",
      "2  3   8   8\n",
      "3  4   9   9\n",
      "4  5  10  10\n",
      "     一   二   三\n",
      "1:   1   2   3\n",
      "2:   4   5   6\n",
      "3:   7   8   9\n",
      "4:  10  11  12\n",
      "   一  二   三\n",
      "a  1  5   9\n",
      "b  2  6  10\n",
      "c  3  7  11\n",
      "d  4  8  12\n"
     ]
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## dataFrame属性",
   "id": "fe361d72b1cbfde"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-20T09:55:05.860071Z",
     "start_time": "2025-08-20T09:55:01.930906Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 属性/方法\t说明\n",
    "# index\tDataFrame 的行索引\n",
    "# values\tDataFrame 的值（NumPy 数组）\n",
    "# dtypes\tDataFrame 的元素类型\n",
    "# shape\tDataFrame 的形状（行数, 列数）\n",
    "# ndim\tDataFrame 的维度（通常是 2）\n",
    "# size\tDataFrame 的元素个数\n",
    "# columns\tDataFrame 的列标签\n",
    "# loc[]\t显式索引，按行列标签索引或切片\n",
    "# iloc[]\t隐式索引，按行列位置索引或切片\n",
    "# at[]\t使用行列标签访问单个元素\n",
    "# iat[]\t使用行列位置访问单个元素\n",
    "# T\t行列转置\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "df = pd.DataFrame([[1,\"a\",True],[4,'b',False],[7,'c',True],[10,'d',False]],columns=[\"num\",\"str\",\"bool\"])\n",
    "\n",
    "print(\"行索引\")\n",
    "print(df.index)\n",
    "print(\"列索引\")\n",
    "print(df.columns)\n",
    "print(\"值\")\n",
    "print(df.values) #二维\n",
    "print(df[\"num\"])"
   ],
   "id": "b72f603e74087518",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "行索引\n",
      "RangeIndex(start=0, stop=4, step=1)\n",
      "列索引\n",
      "Index(['num', 'str', 'bool'], dtype='object')\n",
      "值\n",
      "[[1 'a' True]\n",
      " [4 'b' False]\n",
      " [7 'c' True]\n",
      " [10 'd' False]]\n",
      "0     1\n",
      "1     4\n",
      "2     7\n",
      "3    10\n",
      "Name: num, dtype: int64\n"
     ]
    }
   ],
   "execution_count": 1
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-23T14:37:19.427716Z",
     "start_time": "2025-07-23T14:37:19.405406Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# dtypes 数据类型\n",
    "print(\"dtypes\")\n",
    "print(df.dtypes)\n",
    "# ndim 维度\n",
    "print(\"ndim\")\n",
    "print(df.ndim)\n",
    "# size 元素个数\n",
    "print(\"size\")\n",
    "print(df.size)\n",
    "# shape 形状\n",
    "print(\"shape\")\n",
    "print(df.shape)\n",
    "# loc[] 显式索引，按行列标签索引或切片\n",
    "print(\"-----------loc-------------\")\n",
    "print(df.loc[0])\n",
    "print(df.loc[0,\"num\"])\n",
    "print(df.loc[0:2])\n",
    "print(df.loc[0:2,\"num\"])\n",
    "\n",
    "# iloc[] 隐式索引，按行列位置索引或切片\n",
    "print(\"-----------iloc-------------\")\n",
    "print(df.iloc[0])\n",
    "print(df.iloc[0:2])\n",
    "\n",
    "# at[] 使用行列标签访问单个元素\n",
    "print(\"-----------at-------------\")\n",
    "print(df.at[0,\"num\"])\n",
    "# iat[] 使用行列位置访问单个元素\n",
    "print(df.iat[0,0])\n",
    "\n",
    "# T 行列转置\n",
    "print(\"-----------T-------------\")\n",
    "print(df.T)"
   ],
   "id": "1e40fc230f8612be",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dtypes\n",
      "num      int64\n",
      "str     object\n",
      "bool      bool\n",
      "dtype: object\n",
      "ndim\n",
      "2\n",
      "size\n",
      "12\n",
      "shape\n",
      "(4, 3)\n",
      "-----------loc-------------\n",
      "num        1\n",
      "str        a\n",
      "bool    True\n",
      "Name: 0, dtype: object\n",
      "   num str   bool\n",
      "0    1   a   True\n",
      "1    4   b  False\n",
      "2    7   c   True\n",
      "0    1\n",
      "1    4\n",
      "2    7\n",
      "Name: num, dtype: int64\n",
      "-----------iloc-------------\n",
      "num        1\n",
      "str        a\n",
      "bool    True\n",
      "Name: 0, dtype: object\n",
      "   num str   bool\n",
      "0    1   a   True\n",
      "1    4   b  False\n",
      "-----------at-------------\n",
      "1\n",
      "1\n",
      "-----------T-------------\n",
      "         0      1     2      3\n",
      "num      1      4     7     10\n",
      "str      a      b     c      d\n",
      "bool  True  False  True  False\n"
     ]
    }
   ],
   "execution_count": 17
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-23T14:59:41.461018Z",
     "start_time": "2025-07-23T14:59:41.424249Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "df = pd.DataFrame([[1,\"a\",True],[4,'b',False],[7,'c',True],[10,'d',False]],columns=[\"num\",\"str\",\"bool\"])\n",
    "#获取单列,如果要通过索引必须经过loc和at等函数，直接使用括号是列\n",
    "print(df[\"str\"])\n",
    "print(df.str)\n",
    "print(type(df.str)) #Series 一列是一个series\n",
    "print(df[[\"str\"]])\n",
    "print(type(df[[\"str\"]])) #DataFrame\n",
    "print(df[[\"num\",\"str\"]]) #两列的dateFrame\n",
    "print(type(df[[\"num\",\"str\"]])) #DataFrame\n",
    "\n",
    "#head\n",
    "print(df.head())\n",
    "print(df.head(2))\n",
    "#tail\n",
    "print(df.tail())\n",
    "print(df.tail(2))\n",
    "\n",
    "#bool过滤\n",
    "print(df[df.num>5])\n",
    "print(\"df[df.num>5][\\\"str\\\"]\")\n",
    "print(df[df.num>5][\"str\"])\n",
    "#多条件\n",
    "print(\"----多条件--------------\")\n",
    "print(df[(df.num>5) & (df.str==\"c\")])\n",
    "\n",
    "#sample随机取样\n",
    "print(\"------sample----------\")\n",
    "print(df.sample())\n",
    "print(df.sample(2)) #随机取样2个\n",
    "\n",
    " \n"
   ],
   "id": "dd6832692c349817",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    a\n",
      "1    b\n",
      "2    c\n",
      "3    d\n",
      "Name: str, dtype: object\n",
      "0    a\n",
      "1    b\n",
      "2    c\n",
      "3    d\n",
      "Name: str, dtype: object\n",
      "<class 'pandas.core.series.Series'>\n",
      "  str\n",
      "0   a\n",
      "1   b\n",
      "2   c\n",
      "3   d\n",
      "<class 'pandas.core.frame.DataFrame'>\n",
      "   num str\n",
      "0    1   a\n",
      "1    4   b\n",
      "2    7   c\n",
      "3   10   d\n",
      "<class 'pandas.core.frame.DataFrame'>\n",
      "   num str   bool\n",
      "0    1   a   True\n",
      "1    4   b  False\n",
      "2    7   c   True\n",
      "3   10   d  False\n",
      "   num str   bool\n",
      "0    1   a   True\n",
      "1    4   b  False\n",
      "   num str   bool\n",
      "0    1   a   True\n",
      "1    4   b  False\n",
      "2    7   c   True\n",
      "3   10   d  False\n",
      "   num str   bool\n",
      "2    7   c   True\n",
      "3   10   d  False\n",
      "   num str   bool\n",
      "2    7   c   True\n",
      "3   10   d  False\n",
      "df[df.num>5][\"str\"]\n",
      "2    c\n",
      "3    d\n",
      "Name: str, dtype: object\n",
      "----多条件--------------\n",
      "   num str  bool\n",
      "2    7   c  True\n",
      "------sample----------\n",
      "   num str   bool\n",
      "1    4   b  False\n",
      "   num str   bool\n",
      "3   10   d  False\n",
      "1    4   b  False\n"
     ]
    }
   ],
   "execution_count": 34
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-23T15:35:13.620670Z",
     "start_time": "2025-07-23T15:35:13.603818Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "df = pd.DataFrame([[1,\"a\",True],[4,'b',False],[7,'c',True],[10,'d',False]],columns=[\"num\",\"str\",\"bool\"])\n",
    "#isin\n",
    "print(\"---------isin---------\")\n",
    "print(df.isin([1,2,3])) #判断是否在列表中\n",
    "\n",
    "#isna 查看元素是否有缺失值\n",
    "print(\"--------isna----------\")\n",
    "print(df.isna())\n",
    "\n",
    "#sum\n",
    "print(\"--------sum----------\")\n",
    "print(df.sum())\n",
    "print(df[\"num\"].sum())\n",
    "print(df.num.sum())\n",
    "\n",
    "#max\n",
    "print(\"--------max----------\")\n",
    "print(df.max())\n",
    "print(df[\"num\"].max())\n",
    "print(df.num.max())\n",
    "\n",
    "#min\n",
    "print(\"--------min----------\")\n",
    "print(df.min())\n",
    "print(type(df.min())) # <class 'pandas.core.series.Series'>\n",
    "\n",
    "print(df[\"num\"].min())\n",
    "print(df.num.min())\n",
    "print(type(df.num.min())) # <class 'numpy.int64'>\n",
    "\n",
    "#mean\n",
    "print(\"--------mean----------\")\n",
    "print(df[\"num\"].mean())\n",
    "print(df.num.mean())\n",
    "print(type(df.num.mean()))\n",
    "\n",
    "#median\n",
    "print(\"--------median----------\")\n",
    "print(df[\"num\"].median())\n",
    "print(df.num.median())\n",
    "print(type(df.num.median()))\n",
    "\n",
    "#std\n",
    "print(\"--------std----------\")\n",
    "print(df[\"num\"].std())\n",
    "print(df.num.std())\n",
    "print(type(df.num.std()))\n"
   ],
   "id": "f8d0a2c72729f842",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "---------isin---------\n",
      "     num    str   bool\n",
      "0   True  False   True\n",
      "1  False  False  False\n",
      "2  False  False   True\n",
      "3  False  False  False\n",
      "--------isna----------\n",
      "     num    str   bool\n",
      "0  False  False  False\n",
      "1  False  False  False\n",
      "2  False  False  False\n",
      "3  False  False  False\n",
      "--------sum----------\n",
      "num       22\n",
      "str     abcd\n",
      "bool       2\n",
      "dtype: object\n",
      "22\n",
      "22\n",
      "--------max----------\n",
      "num       10\n",
      "str        d\n",
      "bool    True\n",
      "dtype: object\n",
      "10\n",
      "10\n",
      "--------min----------\n",
      "num         1\n",
      "str         a\n",
      "bool    False\n",
      "dtype: object\n",
      "<class 'pandas.core.series.Series'>\n",
      "1\n",
      "1\n",
      "<class 'numpy.int64'>\n",
      "--------mean----------\n",
      "5.5\n",
      "5.5\n",
      "<class 'numpy.float64'>\n",
      "--------median----------\n",
      "5.5\n",
      "5.5\n",
      "<class 'numpy.float64'>\n",
      "--------std----------\n",
      "3.872983346207417\n",
      "3.872983346207417\n",
      "<class 'numpy.float64'>\n"
     ]
    }
   ],
   "execution_count": 48
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-20T09:58:25.355436Z",
     "start_time": "2025-08-20T09:58:25.130804Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#describe 忽略字符串列\n",
    "print(\"--------describe----------\")\n",
    "print(df.describe())\n",
    "print(\"--------describe2----------\")\n",
    "print(df.num.describe())\n"
   ],
   "id": "a39bcbb6b8cd3f34",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--------describe----------\n",
      "             num\n",
      "count   4.000000\n",
      "mean    5.500000\n",
      "std     3.872983\n",
      "min     1.000000\n",
      "25%     3.250000\n",
      "50%     5.500000\n",
      "75%     7.750000\n",
      "max    10.000000\n",
      "--------describe2----------\n",
      "count     4.000000\n",
      "mean      5.500000\n",
      "std       3.872983\n",
      "min       1.000000\n",
      "25%       3.250000\n",
      "50%       5.500000\n",
      "75%       7.750000\n",
      "max      10.000000\n",
      "Name: num, dtype: float64\n"
     ]
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-07T15:58:07.633131Z",
     "start_time": "2025-08-07T15:58:07.616576Z"
    }
   },
   "cell_type": "code",
   "source": [
    "df = pd.DataFrame([[1,\"a\",True],[4,'b',False],[7,'c',True],[10,'d',False]],columns=[\"num\",\"str\",\"bool\"])\n",
    "\n",
    "print(df)\n",
    "#count\n",
    "print(\"--------count----------\")\n",
    "print(df.count())\n",
    "\n",
    "#value_counts 每行的所有列完全相同的行只算1行\n",
    "df = pd.DataFrame([[1,\"a\",True],[4,'b',False],[7,'c',True],[10,'d',False],[1,\"a\",True]],columns=[\"num\",\"str\",\"bool\"])\n",
    "print(\"--------value_counts----------\")\n",
    "print(df.value_counts())\n",
    "\n",
    "#去重drop_duplicates 删除所有列完全相同的行\n",
    "print(\"--------drop_duplicates----------\")\n",
    "print(df.drop_duplicates())\n",
    "\n",
    "#duplicate\n",
    "print(\"--------duplicated----------\")\n",
    "print(df.duplicated()) #显示是否重复,第一次出现为False，后面重复出现为True\n",
    "print(df.duplicated(subset=[\"bool\"])) #指定列\n",
    "\n",
    "#replace 替换\n",
    "print(\"--------replace----------\")\n",
    "print(df.replace(1,100))\n",
    "\n",
    "#cumsum 直到当前的和\n",
    "print(\"--------cumsum----------\")\n",
    "print(df.num.cumsum())\n",
    "# print(df.num.cumsum(axis=1)) #行求和\n",
    "\n",
    "#cunmax 直到当前的最大值\n",
    "print(\"--------cummax----------\")\n",
    "print(df.num.cummax())"
   ],
   "id": "3be92e36af2548dc",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   num str   bool\n",
      "0    1   a   True\n",
      "1    4   b  False\n",
      "2    7   c   True\n",
      "3   10   d  False\n",
      "--------count----------\n",
      "num     4\n",
      "str     4\n",
      "bool    4\n",
      "dtype: int64\n",
      "--------value_counts----------\n",
      "num  str  bool \n",
      "1    a    True     2\n",
      "4    b    False    1\n",
      "7    c    True     1\n",
      "10   d    False    1\n",
      "Name: count, dtype: int64\n",
      "--------drop_duplicates----------\n",
      "   num str   bool\n",
      "0    1   a   True\n",
      "1    4   b  False\n",
      "2    7   c   True\n",
      "3   10   d  False\n",
      "--------duplicated----------\n",
      "0    False\n",
      "1    False\n",
      "2    False\n",
      "3    False\n",
      "4     True\n",
      "dtype: bool\n",
      "0    False\n",
      "1    False\n",
      "2     True\n",
      "3     True\n",
      "4     True\n",
      "dtype: bool\n",
      "--------replace----------\n",
      "   num str   bool\n",
      "0  100   a   True\n",
      "1    4   b  False\n",
      "2    7   c   True\n",
      "3   10   d  False\n",
      "4  100   a   True\n",
      "--------cumsum----------\n",
      "0     1\n",
      "1     5\n",
      "2    12\n",
      "3    22\n",
      "4    23\n",
      "Name: num, dtype: int64\n",
      "--------cummax----------\n",
      "0     1\n",
      "1     4\n",
      "2     7\n",
      "3    10\n",
      "4    10\n",
      "Name: num, dtype: int64\n"
     ]
    }
   ],
   "execution_count": 16
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-23T16:16:59.835992Z",
     "start_time": "2025-07-23T16:16:59.806206Z"
    }
   },
   "cell_type": "code",
   "source": [
    "df = pd.DataFrame([[1,\"a\",True],[4,'b',False],[7,'c',True],[10,'d',False],[1,\"a\",True]],columns=[\"num\",\"str\",\"bool\"])\n",
    "\n",
    "#sort_index todo 复习\n",
    "print(\"--------sort_index----------\")\n",
    "print(df.sort_index())\n",
    "print(df.sort_index(ascending=False))\n",
    "# print(df.sort_index(axis=0))\n",
    "# print(df.sort_index(axis=1)) #列排序\n",
    "\n",
    "#sort_values\n",
    "print(\"--------sort_values----------\")\n",
    "print(df.sort_values(by=\"num\"))\n",
    "print(df.sort_values(by=\"num\",ascending=False))\n",
    "#多列排序\n",
    "print(df.sort_values(by=[\"num\",\"str\"]))\n",
    "print(df.sort_values(by=[\"num\",\"str\"],ascending=[True,False]))\n",
    "\n",
    "#nlargest\n",
    "print(\"--------nlargest----------\")\n",
    "print(df.nlargest(2,[\"num\"]))\n",
    "print(df.nlargest(2,[\"bool\"]))\n",
    "print(df.nlargest(2,[\"num\",\"bool\"]))"
   ],
   "id": "87cab8872defcd72",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--------sort_index----------\n",
      "   num str   bool\n",
      "0    1   a   True\n",
      "1    4   b  False\n",
      "2    7   c   True\n",
      "3   10   d  False\n",
      "4    1   a   True\n",
      "   num str   bool\n",
      "4    1   a   True\n",
      "3   10   d  False\n",
      "2    7   c   True\n",
      "1    4   b  False\n",
      "0    1   a   True\n",
      "--------sort_values----------\n",
      "   num str   bool\n",
      "0    1   a   True\n",
      "4    1   a   True\n",
      "1    4   b  False\n",
      "2    7   c   True\n",
      "3   10   d  False\n",
      "   num str   bool\n",
      "3   10   d  False\n",
      "2    7   c   True\n",
      "1    4   b  False\n",
      "0    1   a   True\n",
      "4    1   a   True\n",
      "   num str   bool\n",
      "0    1   a   True\n",
      "4    1   a   True\n",
      "1    4   b  False\n",
      "2    7   c   True\n",
      "3   10   d  False\n",
      "   num str   bool\n",
      "0    1   a   True\n",
      "4    1   a   True\n",
      "1    4   b  False\n",
      "2    7   c   True\n",
      "3   10   d  False\n",
      "--------nlargest----------\n",
      "   num str   bool\n",
      "3   10   d  False\n",
      "2    7   c   True\n",
      "   num str  bool\n",
      "0    1   a  True\n",
      "2    7   c  True\n",
      "   num str   bool\n",
      "3   10   d  False\n",
      "2    7   c   True\n"
     ]
    }
   ],
   "execution_count": 69
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 综合案例",
   "id": "ba42c5a18a141171"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-23T16:56:22.361194Z",
     "start_time": "2025-07-23T16:56:22.308519Z"
    }
   },
   "cell_type": "code",
   "source": [
    "'''\n",
    "案例1：学生成绩分析\n",
    "场景：某班级的学生成绩数据如下，请完成以下任务：\n",
    "1. 计算每位学生的总分和平均分。\n",
    "2. 找出数学成绩高于90分或英语成绩高于85分的学生。\n",
    "3. 按总分从高到低排序，并输出前3名学生。\n",
    "'''\n",
    "import pandas as pd\n",
    "data = {\n",
    "    '姓名': ['张三', '李四', '王五', '赵六', '钱七'],\n",
    "    '数学': [85, 92, 78, 88, 95],\n",
    "    '英语': [90, 88, 85, 92, 80],\n",
    "    '物理': [75, 80, 88, 85, 90]\n",
    "}\n",
    "scores = pd.DataFrame(data)\n",
    "print(scores)\n",
    "#    姓名  数学  英语  物理\n",
    "# 0  张三  85  90  75\n",
    "# 1  李四  92  88  80\n",
    "# 2  王五  78  85  88\n",
    "# 3  赵六  88  92  85\n",
    "# 4  钱七  95  80  90\n",
    "print(\"----1. 计算每位学生的总分和平均分-----\")\n",
    "# print(scores.iloc[:,1:3].sum(axis=1))\n",
    "# print(scores.iloc[:,1:3].mean(axis=1))\n",
    "#scores.iloc[:,1:3].sum(axis=1)和name组合\n",
    "#吧scores.iloc[:,1:3].sum(axis=1)和姓名组成新的dataFrame\n",
    "print(\"----------方法1-------------\")\n",
    "# print(pd.DataFrame(scores['姓名'],scores.iloc[:,1:3].sum(axis=1),columns=['姓名','总分'])) #错误，这种方式传入的一列应该是一行属性，而非一列属性\n",
    "# 方法1：使用字典形式（推荐）\n",
    "print(pd.DataFrame({\n",
    "    '姓名': scores['姓名'], \n",
    "    '总分': scores.iloc[:,1:3].sum(axis=1)\n",
    "}))\n",
    "\n",
    "# 方法2：使用assign方法\n",
    "print(pd.DataFrame({'姓名': scores['姓名']}).assign(总分=scores.iloc[:,1:3].sum(axis=1)))\n",
    "\n",
    "\n",
    "#修复\n",
    "print(\"----------方法2-------------\")\n",
    "\n",
    "scores['总分'] = scores.iloc[:,1:3].sum(axis=1)\n",
    "scores['平均分'] = scores.iloc[:,1:3].mean(axis=1)\n",
    "print(scores)\n",
    "\n",
    "print(\"----2. 找出数学成绩高于90分或英语成绩高于85分的学生-----\")\n",
    "print(scores[(scores['数学']>90) | (scores['英语']>85)])\n",
    "\n",
    "print(\"----3. 按总分从高到低排序，并输出前3名学生-----\")\n",
    "print(scores.sort_values(by='总分',ascending=False))\n",
    "print(scores.sort_values(by='总分',ascending=False).head(3))\n",
    "print(scores.nlargest(3,columns=['总分']))\n",
    "\n",
    "\n",
    "print(\"----视频解法-----\")\n",
    "\n",
    "#1. 计算每位学生的总分和平均分。\n",
    "scores['总分'] = scores[['数学','英语','物理']].sum(axis=1)\n",
    "scores['平均分'] = scores['总分'] / 3\n",
    "scores['平均分2'] = scores[['数学','英语','物理']].mean(axis=1)\n",
    "#2. 找出数学成绩高于90分或英语成绩高于85分的学生。\n",
    "scores[ (scores['数学']>90 ) | (scores['英语']>85 )  ]\n",
    "#3. 按总分从高到低排序，并输出前3名学生。\n",
    "r1 = scores.sort_values('总分',ascending=False).head(3)\n",
    "r2 =scores.nlargest(3,columns=['总分'])\n",
    "print(r1)\n",
    "print(r2)"
   ],
   "id": "bdaca28106c33679",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   姓名  数学  英语  物理\n",
      "0  张三  85  90  75\n",
      "1  李四  92  88  80\n",
      "2  王五  78  85  88\n",
      "3  赵六  88  92  85\n",
      "4  钱七  95  80  90\n",
      "----1. 计算每位学生的总分和平均分-----\n",
      "----------方法1-------------\n",
      "   姓名   总分\n",
      "0  张三  175\n",
      "1  李四  180\n",
      "2  王五  163\n",
      "3  赵六  180\n",
      "4  钱七  175\n",
      "   姓名   总分\n",
      "0  张三  175\n",
      "1  李四  180\n",
      "2  王五  163\n",
      "3  赵六  180\n",
      "4  钱七  175\n",
      "----------方法2-------------\n",
      "   姓名  数学  英语  物理   总分   平均分\n",
      "0  张三  85  90  75  175  87.5\n",
      "1  李四  92  88  80  180  90.0\n",
      "2  王五  78  85  88  163  81.5\n",
      "3  赵六  88  92  85  180  90.0\n",
      "4  钱七  95  80  90  175  87.5\n",
      "----2. 找出数学成绩高于90分或英语成绩高于85分的学生-----\n",
      "   姓名  数学  英语  物理   总分   平均分\n",
      "0  张三  85  90  75  175  87.5\n",
      "1  李四  92  88  80  180  90.0\n",
      "3  赵六  88  92  85  180  90.0\n",
      "4  钱七  95  80  90  175  87.5\n",
      "----3. 按总分从高到低排序，并输出前3名学生-----\n",
      "   姓名  数学  英语  物理   总分   平均分\n",
      "1  李四  92  88  80  180  90.0\n",
      "3  赵六  88  92  85  180  90.0\n",
      "0  张三  85  90  75  175  87.5\n",
      "4  钱七  95  80  90  175  87.5\n",
      "2  王五  78  85  88  163  81.5\n",
      "   姓名  数学  英语  物理   总分   平均分\n",
      "1  李四  92  88  80  180  90.0\n",
      "3  赵六  88  92  85  180  90.0\n",
      "0  张三  85  90  75  175  87.5\n",
      "   姓名  数学  英语  物理   总分   平均分\n",
      "1  李四  92  88  80  180  90.0\n",
      "3  赵六  88  92  85  180  90.0\n",
      "0  张三  85  90  75  175  87.5\n",
      "----视频解法-----\n",
      "   姓名  数学  英语  物理   总分        平均分       平均分2\n",
      "4  钱七  95  80  90  265  88.333333  88.333333\n",
      "3  赵六  88  92  85  265  88.333333  88.333333\n",
      "1  李四  92  88  80  260  86.666667  86.666667\n",
      "   姓名  数学  英语  物理   总分        平均分       平均分2\n",
      "3  赵六  88  92  85  265  88.333333  88.333333\n",
      "4  钱七  95  80  90  265  88.333333  88.333333\n",
      "1  李四  92  88  80  260  86.666667  86.666667\n"
     ]
    }
   ],
   "execution_count": 91
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-07T15:32:30.130737Z",
     "start_time": "2025-08-07T15:32:29.418156Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import pandas as pd\n",
    "data = {\n",
    "    '姓名': ['张三', '李四', '王五', '赵六', '钱七'],\n",
    "    '数学': [85, 92, 78, 88, 95],\n",
    "    '英语': [90, 88, 85, 92, 80],\n",
    "    '物理': [75, 80, 88, 85, 90]\n",
    "}\n",
    "pd = pd.DataFrame(data)\n",
    "print( pd)\n",
    "#获取行\n",
    "print(\"----loc---------\")\n",
    "print(pd.loc[0])\n",
    "print(pd.loc[0:2])\n",
    "print(pd.loc[:,'姓名'])\n",
    "print(pd.loc[:,['姓名','数学']]) #获取多列 类似pd.loc[['姓名','数学']]\n",
    "\n",
    "print(\"----iloc---------\")\n",
    "print(pd.iloc[0])\n",
    "print(pd.iloc[0,0])\n",
    "\n",
    "print(\"----at---------\")\n",
    "print(pd.at[0,'数学'])\n",
    "print(pd.iat[0,1])\n",
    "# print(pd[0]) #错误\n",
    "# print(pd[1]) #错误\n",
    "\n",
    "#获取列\n",
    "print(pd[\"数学\"])\n",
    "print(pd.数学)\n"
   ],
   "id": "433e8d125525a4b8",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   姓名  数学  英语  物理\n",
      "0  张三  85  90  75\n",
      "1  李四  92  88  80\n",
      "2  王五  78  85  88\n",
      "3  赵六  88  92  85\n",
      "4  钱七  95  80  90\n",
      "----loc---------\n",
      "姓名    张三\n",
      "数学    85\n",
      "英语    90\n",
      "物理    75\n",
      "Name: 0, dtype: object\n",
      "   姓名  数学  英语  物理\n",
      "0  张三  85  90  75\n",
      "1  李四  92  88  80\n",
      "2  王五  78  85  88\n",
      "0    张三\n",
      "1    李四\n",
      "2    王五\n",
      "3    赵六\n",
      "4    钱七\n",
      "Name: 姓名, dtype: object\n",
      "   姓名  数学\n",
      "0  张三  85\n",
      "1  李四  92\n",
      "2  王五  78\n",
      "3  赵六  88\n",
      "4  钱七  95\n",
      "----iloc---------\n",
      "姓名    张三\n",
      "数学    85\n",
      "英语    90\n",
      "物理    75\n",
      "Name: 0, dtype: object\n",
      "张三\n",
      "----at---------\n",
      "85\n",
      "85\n",
      "0    85\n",
      "1    92\n",
      "2    78\n",
      "3    88\n",
      "4    95\n",
      "Name: 数学, dtype: int64\n",
      "0    85\n",
      "1    92\n",
      "2    78\n",
      "3    88\n",
      "4    95\n",
      "Name: 数学, dtype: int64\n"
     ]
    }
   ],
   "execution_count": 1
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-07T15:45:13.467694Z",
     "start_time": "2025-08-07T15:45:13.444815Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "'''\n",
    "案例2：销售数据分析\n",
    "场景：某公司销售数据如下，请完成以下任务：\n",
    "1. 计算每种产品的总销售额（销售额 = 单价 × 销量）。\n",
    "2. 找出销售额最高的产品。\n",
    "3. 按销售额从高到低排序，并输出所有产品信息。\n",
    "'''\n",
    "import pandas as pd\n",
    "\n",
    "data = {\n",
    "    '产品名称': ['A', 'B', 'C', 'D'],\n",
    "    '单价': [100, 150, 200, 120],\n",
    "    '销量': [50, 30, 20, 40]\n",
    "}\n",
    "df = pd.DataFrame(data)\n",
    "df['总销售额'] = df['单价'] * df['销量']\n",
    "print(df)\n",
    "print(df.nlargest(1,columns=['总销售额']))\n",
    "print(df.sort_values(by='总销售额',ascending=False))\n",
    "\n"
   ],
   "id": "28c4ee9fb700efd2",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  产品名称   单价  销量  总销售额\n",
      "0    A  100  50  5000\n",
      "1    B  150  30  4500\n",
      "2    C  200  20  4000\n",
      "3    D  120  40  4800\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-07T15:49:34.905065Z",
     "start_time": "2025-08-07T15:49:34.889269Z"
    }
   },
   "cell_type": "code",
   "source": [
    "'''案例3：电商用户行为分析\n",
    "场景：某电商平台的用户行为数据如下，请完成以下任务：\n",
    "1. 计算每位用户的总消费金额（消费金额 = 商品单价 × 购买数量）\n",
    "2. 找出消费金额最高的用户，并输出其所有信息\n",
    "3. 计算所有用户的平均消费金额（保留2位小数）\n",
    "4. 统计电子产品的总购买数量\n",
    "'''\n",
    "import pandas as pd\n",
    "\n",
    "data = {\n",
    "    '用户ID': [101, 102, 103, 104, 105],\n",
    "    '用户名': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],\n",
    "    '商品类别': ['电子产品', '服饰', '电子产品', '家居', '服饰'],\n",
    "    '商品单价': [1200, 300, 800, 150, 200],\n",
    "    '购买数量': [1, 3, 2, 5, 4]\n",
    "}\n",
    "df = pd.DataFrame(data)\n",
    "print(df)\n",
    "df['总销售额'] = df['商品单价'] * df['购买数量']\n",
    "print(df)\n",
    "print(df.nlargest(1,columns=['总销售额']))\n",
    "print(df['总销售额'].mean())\n",
    "print(df[df['商品类别'] == '电子产品']['购买数量'].sum())"
   ],
   "id": "6bfbdbf93f0c05e3",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   用户ID      用户名  商品类别  商品单价  购买数量\n",
      "0   101    Alice  电子产品  1200     1\n",
      "1   102      Bob    服饰   300     3\n",
      "2   103  Charlie  电子产品   800     2\n",
      "3   104    David    家居   150     5\n",
      "4   105      Eve    服饰   200     4\n",
      "   用户ID      用户名  商品类别  商品单价  购买数量  总销售额\n",
      "0   101    Alice  电子产品  1200     1  1200\n",
      "1   102      Bob    服饰   300     3   900\n",
      "2   103  Charlie  电子产品   800     2  1600\n",
      "3   104    David    家居   150     5   750\n",
      "4   105      Eve    服饰   200     4   800\n",
      "   用户ID      用户名  商品类别  商品单价  购买数量  总销售额\n",
      "2   103  Charlie  电子产品   800     2  1600\n",
      "1050.0\n",
      "3\n"
     ]
    }
   ],
   "execution_count": 12
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
